package com.atguigu.bigdata.spark.core.rdd.operator.transform;

import org.apache.spark.HashPartitioner;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.sql.sources.In;
import scala.Tuple2;

import java.util.Arrays;
import java.util.List;

public class Spark14_RDD_Operator_Transform_JAVA {
    public static void main(String[] args) {
        SparkConf conf = new SparkConf().setMaster("local[*]").setAppName("sparkCore");
        JavaSparkContext sc = new JavaSparkContext(conf);

        List<Integer> list = Arrays.asList(1,2,3,4,5);
        JavaRDD<Integer> rdd =sc.parallelize(list, 2);
        // TODO 算子 - (Key - Value类型)
        // RDD => PairRDDFunctions
        // 隐式转换（二次编译）
        // partitionBy根据指定的分区规则对数据进行重分区

        JavaPairRDD<Integer, Integer> mapPair = rdd.mapToPair(new PairFunction<Integer, Integer, Integer>() {
            @Override
            public Tuple2<Integer, Integer> call(Integer integer) throws Exception {
                if(integer % 2 == 0) {
                    return new Tuple2<Integer, Integer>(0, integer);
                } else {
                    return new Tuple2<Integer, Integer>(1, integer);
                }
            }
        });

        JavaPairRDD<Integer, Integer> res = mapPair.partitionBy(new HashPartitioner(3));

        res.saveAsTextFile("output");

        sc.stop();

    }
}
